<template>
  <div class="playback-container">
    <div class="check">
      <section class="check-one">
        <el-radio-group v-model="radio" class="check-btn">
          <p class="check-btn">回放查看设置：</p>
          <el-radio label="0">不允许查看</el-radio>
          <el-radio label="1">允许查看</el-radio>
        </el-radio-group>
        <section class="check-two check-btn">
          <p v-show="radio =='1' ? true : false" class="check-btn">回放范围设置：</p>
          <el-radio-group v-show="radio =='1' ? true : false" v-model="radioList" class="check-btn">
            <el-radio label="0">公众用户</el-radio>
            <el-radio label="1">注册用户</el-radio>
            <el-radio label="2">认证用户</el-radio>
            <el-radio label="5">与直播活动一致</el-radio>
          </el-radio-group>
          <el-button type="primary" @click="handleSetting">确定</el-button>
        </section>
      </section>
    </div>
    <div class="center-btn">
      <div class="title">直播回放</div>
      <div>
        <el-button @click="backplay">返回</el-button>
        <el-button @click="createPlay">添加回放</el-button>
      </div>
    </div>
    <div class="search-tabel">
      <v-table :list="tableData" tag="playBack" :list-loading="listLoading" :filter-column="filtercolumn">
        <el-table-column
          fixed="right"
          label="操作"
          width="400"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="text" size="small" @click="editPlay(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handlePublish(scope.row)">{{ scope.row.publishStatus === "GIPSTSTUS01" ? "取消发布" : "发布" }}</el-button>
          </template>
        </el-table-column>
      </v-table>
    </div>
    <div class="footer">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <!--  添加回放-->
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      title="添加/编辑"
      :visible.sync="dialogFormVisible"
      center
      width="600px"
      top="10vh"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        :rules="rules"
        class="dataForm"
        label-position="right"
        label-width="107px"
        style="padding-right: 10px;height:400px;overflow: auto;"
      >
        <el-form-item label="回放类型" prop="type">
          <el-radio-group
            v-model="temp.type"
            placeholder="请选择"
            style="width: 100%"
            :disabled="state!=='create' || pageType==='LIVETYPE_LINK'"
          >
            <el-radio
              v-for="(item,index) in dict.HFLX"
              :key="index"
              :label="item.dictValue"
            >{{ item.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="temp.type==='HFLX_ZY'">
          <el-form-item v-if="state==='create'" label="选择视频" prop="video">
            <el-select
              v-model="temp.video"
              placeholder="请选择"
              style="width: 100%"
              @change="handleChagne"
            >
              <el-option
                v-for="(item,index) in options"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </template>
        <template v-if="temp.type==='HFLX_DSF'&& state==='create'">
          <el-form-item v-if="state==='create'" label="回放地址" prop="replayUrl">
            <el-input v-model.trim="temp.replayUrl" placeholder="请输入回放地址" />
          </el-form-item>
          <el-form-item v-if="state==='create'" label="开始时间" prop="startTime">
            <el-date-picker
              v-model="temp.startTime"
              style="width:100%;"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择开始时间"
            />
          </el-form-item>
          <el-form-item v-if="state==='create'" label="结束时间" prop="stopTime">
            <el-date-picker
              v-model="temp.stopTime"
              style="width:100%;"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择结束时间"
            />
          </el-form-item>
        </template>
        <el-form-item label="回放标题" prop="title">
          <el-input v-model.trim="temp.title" placeholder="请输入回放标题" />
        </el-form-item>
        <el-form-item label="回放说明" prop="desc">
          <el-input v-model.trim="temp.desc" type="textarea" placeholder="请输入回放说明" />
        </el-form-item>
        <el-form-item label="状态" prop="publishStatus">
          <el-radio-group v-model="temp.publishStatus">
            <el-radio label="GIPSTSTUS01">发布</el-radio>
            <el-radio label="GIPSTSTUS02">不发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可见范围" prop="checked">
          <el-checkbox v-model="temp.liveRange" true-label="5" @change="handleChange">与回放设置一致</el-checkbox>
        </el-form-item>
        <el-form-item v-show="temp.liveRange !== '5' ? true : false" prop="range">
          <el-radio-group v-model="temp.liveRange">
            <el-radio :label="1">公众用户</el-radio>
            <el-radio :label="2">注册用户</el-radio>
            <el-radio :label="3">认证用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="temp.sort" placeholder="请输入排序（序号越大，越靠前）" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="dialogFormVisible = false">取消</el-button>
        <el-button
          style="padding: 8px 30px;"
          type="primary"
          @click="onSubmit"
        >确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import VTable from '@/components/Table'
import {
  updateStatePlayBack,
  queryCCPlayback,
  livePlaybackInfoupdate,
  livePlaybackInfoInsert,
  getSetting,
  livePlaybackInfosetSetting,
  livePlaybackInfoqueryPage,
  delPlayBack,
  getDictByCode
} from '../api'
export default {
  name: 'LivePlayback',
  components: { Pagination, VTable },
  directives: { elDragDialog },
  data() {
    return {
      // 回放id
      recordId: '',
      value1: '',
      value2: '',
      listQuery: {
        page: 1,
        limit: 10,
        liveStartTime: ''
      },
      radio: '',
      radioList: '',
      // 表体数据
      tableData: [],
      total: 0,
      dialogFormVisible: false,
      multipleTable: [],
      temp: {
        video: '',
        replayUrl: '',
        title: '',
        desc: '',
        publishStatus: '',
        liveRange: '',
        sort: '',
        type: '',
        startTime: '',
        stopTime: ''
      },
      rules: {
        type: [
          { required: true, message: '请选择回放类型', trigger: 'change' }
        ],
        video: [
          { required: true, message: '请选择回放视频', trigger: 'change' }
        ],
        replayUrl: [
          { required: true, message: '请输入回放地址', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        stopTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入回放标题', trigger: 'blur' },
          { min: 1, max: 40, message: '请输入长度在1到40之间的字符', trigger: 'blur' }
        ]
      },
      options: [],
      listLoading: false,
      selectObj: {},
      state: 'create',
      dict: {
        'HFLX': []
      },
      pageType: '',
      backItem: ''
    }
  },
  watch: {
    // "temp.type":{
    //   handler(val){
    //       if(val==='HFLX_DSF'){
    //           console.log('直播的对象',this.backItem)
    //         this.handleReset().then(()=>{
    //           this.temp.replayUrl=this.backItem.checkUrl
    //           this.temp.startTime=this.backItem.liveStartTime
    //           this.temp.stopTime=this.backItem.liveEndTime
    //         })
    //       }
    //   }
    // },
    // deep:true
  },
  created() {
    if (this.$route.query.i) {
      this.pageType = this.$route.query.t
      this.backItem = JSON.parse(this.$route.query.r)
      this.getList()
      this.getCCVideoList()
      this.getSetting()
      this.getDict('HFLX')
      if (this.pageType === 'LIVETYPE_LINK') {
        this.temp.type = 'HFLX_DSF'
      }
    } else {
      this.$message.error('页面参数错误')
      this.$router.back()
    }
  },
  methods: {
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode({ dictCode: code }).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },
    backplay() {
      this.$router.back()
    },
    createPlay() {
      this.state = 'create'
      this.handleReset().then(() => {
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },

    editPlay(row) {
      this.state = 'update'
      this.temp = Object.assign({}, row)
      this.dialogFormVisible = true
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleChange() {
      this.temp.range = []
    },
    filtercolumn(scope, item) {
      if (item === 'cyrsrc') {
        return scope.row['joinPeopleNumber'] + '/' + scope.row['joinPeopleTime']
      } else {
        return scope.row[item]
      }
    },
    /**
     * 发布/取消发布
     */
    handlePublish(row) {
      this.$confirm(row.publishStatus === 'GIPSTSTUS01' ? '确认取消发布？' : '确认发布？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateStatePlayBack({ id: row.id, publishStatus: row.publishStatus === 'GIPSTSTUS01' ? 'GIPSTSTUS02' : 'GIPSTSTUS01' }).then(res => {
          if (res.data.code === '200') {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          }
        })
      }).catch(() => {

      })
    },
    getList(obj) {
      this.listLoading = true
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        liveActivityId: this.$route.query.i,
        ccRoomId: this.$route.query.c || ''
      }
      return new Promise((resolve, reject) => {
        livePlaybackInfoqueryPage(query).then(response => {
          this.tableData = response.data.data.rows
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },
    getCCVideoList() {
      const tem = {
        liveActivityId: this.$route.query.i,
        ccRoomId: this.$route.query.c
      }
      queryCCPlayback(tem).then(res => {
        if (res.data.code === '200') {
          this.options = res.data.data.map(i => { return { label: `${i.stopTime} / ${i.liveRecordId} / ${i.title}`, value: i } })
        }
      })
    },
    onSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading'
          })

          if (this.state === 'create') {
            const params = Object.assign({}, this.selectObj, this.temp)
            delete params.video
            if (this.temp.type === 'HFLX_DSF') {
              params.liveActivityId = this.$route.query.i
            }
            return new Promise((resolve, reject) => {
              livePlaybackInfoInsert(params).then(() => {
                this.dialogFormVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success'
                })
                this.getList()
                resolve()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            const params = Object.assign({}, this.selectObj, this.temp)
            delete params.video
            delete params.replayUrl
            delete params.publishStatusValue
            if (this.temp.type === 'HFLX_DSF') {
              params.liveActivityId = this.$route.query.i
            }
            return new Promise((resolve, reject) => {
              livePlaybackInfoupdate(params).then(() => {
                this.dialogFormVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '编辑成功',
                  type: 'success'
                })
                this.getList()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          }
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          delPlayBack({ id: row.id }).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
            this.getCCVideoList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSetting() {
      if (this.radio === '1' && !this.radioList) {
        return this.$message({ message: '请设置回放范围', type: 'warning' })
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      livePlaybackInfosetSetting({ liveActivityId: this.$route.query.i, recordRange: this.radioList, isRecord: this.radio }).then(res => {
        loading.close()
        this.$message({
          type: 'success',
          message: '操作成功！'
        })
      }).catch(error => { loading.close(error) })
    },
    getSetting() {
      getSetting({ liveActivityId: this.$route.query.i }).then(res => {
        this.radio = res.data.data.isRecord
        this.radioList = res.data.data.recordRange
      })
    },
    handleReset() {
      return new Promise((resolve, reject) => {
        for (const i in this.temp) {
          if (Array.isArray(this.temp[i])) {
            this.temp[i] = []
          } else if (i === 'liveRange') {
            this.temp[i] = '5'
          } else if (i === 'publishStatus') {
            this.temp[i] = 'GIPSTSTUS01'
          } else if (i === 'type') {
            break
          } else {
            this.temp[i] = ''
          }
        }
        delete this.temp.startTime
        delete this.temp.stopTime
        this.selectObj = {}
        if (this.pageType === 'LIVETYPE_LINK') {
          this.temp.replayUrl = this.backItem.checkUrl
          this.$set(this.temp, 'startTime', this.backItem.liveStartTime)
          this.$set(this.temp, 'stopTime', this.backItem.liveEndTime)
          this.temp.title = this.backItem.liveName
        }
        resolve()
      })
    },
    handleChagne(i) {
      this.selectObj = i
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss">
.playback-container{
  padding: 10px;
.search{
  position: relative;
  padding-bottom: 30px;
  .search{
    position: absolute;
    height: 50px;
    width: 100%;
    background-color: #fff;
    .search-play{
       white-space: nowrap;
      position: relative;
      left: 20%;
      .search-time{
        display: inline-block;
        /*position: absolute;
        left: 12%;
        height: 50px;
        line-height: 50px;
        text-align: center;
        font-size: 16px;
        margin: 0;*/
      }
      .block{
        display: inline-block;
        /* position: absolute;
         top: 5px;
         left: 30%;*/
      }

    }
    .button-group{
      position: absolute;
      top: 10px;
      margin-left: 70%;
      button{
        background-color: red;
        border: none;
        margin-right: 10px;
        color: #fff;
      }
    }
  }
  }
.check{
  .check-one{
    background-color: #fff;
    padding:5px 15px;
    display:flex;
    .el-button{
      position: relative;
      left: 5%;
    }
    .check-two{
      margin-left: 20px;
      flex: 1;
    }
    .check-btn{
      display: inline-block;
      font-size: 14px;
      color: #a6a6a6;
    }
  }
}
.center-btn{
 width: 100%;
 padding: 5px;
 display: flex;
 justify-content: space-between;
 .title{
    line-height: 36px;
    font-size: 16px;
    font-weight: bold;
    color: #333;
 }
  }
.search-tabel{
  position: relative;
  top: 20px;
}
.footer{
  margin-top: 20px;
  position: relative;
}
}

.dialog-btn{
  position: relative;
  top: 15px;
  float: right;
}

</style>
